﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer;
using DataAccessLayer;
using MyException;

namespace Stationery_Store_Inventory_Management
{
    public partial class UpdateDisbursementList : System.Web.UI.Page
    {
        DisbursementListController dListCont;
        String userName;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                #region Check if user exists and has permission to view this page
                if (Session["UserLoggedIn"] != null)
                {
                    List<string> list = Session["UserLoggedIn"] as List<string>;
                    if (list[0].Equals("validuser"))
                    {
                        int roleId = Convert.ToInt32(list[6]);
                        if (roleId != 5)
                        {
                            Response.Redirect("/AccessDenied.aspx");
                        }
                    }
                    else
                    {
                        Response.Redirect("/Login.aspx");
                    }
                }
                else
                {
                    Response.Redirect("/Login.aspx");
                }
                #endregion

                dListCont = new DisbursementListController();

                if (!IsPostBack)
                {
                    PopulateCollectionPoint();
                    PopulateCategory();
                    PopulateItemName();
                    lblMessage.Text = "";
                    HideFields();
                }
            }
            catch (Exception ex)
            {
            }
        }

        protected void Categoryddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int catId = Convert.ToInt32(Categoryddl.SelectedValue);
                List<Stationery> items = dListCont.getStationeryNamesCont(catId);
                ItemNameddl.DataValueField = "ItemCode";
                ItemNameddl.DataTextField = "ItemName";
                ItemNameddl.DataSource = items;
                ItemNameddl.DataBind();
            }
            catch (Exception ex)
            {
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                lblMessage.Text = "";
                HideAjustmentFields();

                int colPointId = Convert.ToInt32(CollectionPointddl.SelectedValue);
                String itemCode = Convert.ToString(ItemNameddl.SelectedValue);
                var result = dListCont.getDisbursementDeptQtybyItemCont(colPointId, itemCode);
                DeptQtyGrid.DataSource = result;
                DeptQtyGrid.DataBind();
                if (result.ToList().Count > 0)
                {
                    //btnRaiseAdjustment.Visible = true;
                    //for (int i = 0; i < DeptQtyGrid.Rows.Count; i++)
                    //{
                    //    TextBox txtActualQty = (TextBox)DeptQtyGrid.Rows[i].FindControl("ActualQty");
                    //    txtActualQty.Enabled = false;
                    //}
                    ShowAdjustmentFields();
                }
                else
                {
                    string itemName = ItemNameddl.SelectedItem.Text;
                    lblMessage.Text = itemName + " is not included in this week's collection at " + CollectionPointddl.SelectedItem.Text;
                    HideAjustmentFields();
                }
            }
            catch (Exception ex)
            {
            }
        }

        //protected void btnRaiseAdjustment_Click(object sender, EventArgs e)
        //{
        //    int adjustAmount = Convert.ToInt32(txtAdjusmentQty.Text.Trim());
        //    String ItemName = Convert.ToString(ItemNameddl.SelectedItem);
        //    string itemCode = ItemNameddl.SelectedValue;
        //    Stationery stationery = dListCont.GetStationeryByItemCode(itemCode);
        //    dListCont.updAdjustmentandStockHistoryCont(adjustAmount, ItemName);
        //    txtAdjusmentQty.Text = "";
        //    HideAjustmentFields();
        //    lblMessage.Text = "The required stock adjustment has been raised. Kindly allocate the remaining quantity to departments.";
        //}

        //protected void btnAllocateQty_RowCommand(object sender, GridViewCommandEventArgs e)
        //{
        //    if (e.CommandName == "btnAllocate")
        //    {
        //        int index = Convert.ToInt32(e.CommandArgument);
        //        TextBox ActualQty = (TextBox)DeptQtyGrid.Rows[index].Cells[1].FindControl("ActualQty");
        //        string drid = DeptQtyGrid.Rows[index].Cells[2].Text;
        //        string avaqty = DeptQtyGrid.Rows[index].Cells[5].Text;
        //        int dReqId = Convert.ToInt32(drid);
        //        int ac = Convert.ToInt32(ActualQty.Text);
        //        dListCont.updActualQtyCont(dReqId, ac);    
        //    }
        //}

        protected void btnAllocate_Click(object sender, EventArgs e)
        {
            // Raise Adjustment
            int adjustAmount = 0;
            String itemName = ""; 
            string itemCode = "";

            // Allocate Disbursement
            int total = 0;
            int actualQty = 0;
            List<int> lstDeptReqDetId = new List<int>();
            List<int> lstAllocatedQty = new List<int>();

            try
            {
                adjustAmount = Convert.ToInt32(txtAdjusmentQty.Text.Trim());
                itemName = Convert.ToString(ItemNameddl.SelectedItem);
                itemCode = ItemNameddl.SelectedValue;
                Stationery stationery = dListCont.GetStationeryByItemCode(itemCode);
                int currentAvailQty = stationery.AvailableQty;

                for (int i = 0; i < DeptQtyGrid.Rows.Count; i++)
                {
                    TextBox txtActualQty = (TextBox)DeptQtyGrid.Rows[i].FindControl("ActualQty");
                    total += Convert.ToInt32(txtActualQty.Text);
                    if (Convert.ToInt32(txtActualQty.Text) > Convert.ToInt32(DeptQtyGrid.Rows[i].Cells[5].Text))
                    {
                        throw new AllocateQtyMoreThanActualQtyException();
                    }
                    actualQty += Convert.ToInt32(DeptQtyGrid.Rows[i].Cells[5].Text);
                    lstAllocatedQty.Add(Convert.ToInt32(txtActualQty.Text));
                    lstDeptReqDetId.Add(Convert.ToInt32(DeptQtyGrid.Rows[i].Cells[1].Text));  
                }
                //if (total + Convert.ToInt32(txtAdjusmentQty.Text) > currentAvailQty)
                if (total + Convert.ToInt32(txtAdjusmentQty.Text) != actualQty)
                {
                    throw new TotalAllocatedQtyMustBeEqualTotalActualQtySubtractAdjustedQtyException();
                }
                else
                {
                    //// Adjustment
                    //dListCont.updAdjustmentandStockHistoryCont(adjustAmount, ItemName);

                    //// Allocate
                    //dListCont.updateDeptReqDetActualQty(lstDeptReqDetId, lstAllocatedQty);
                    dListCont.UpdateDeptReqDetAndAdjAndStockHistory(adjustAmount, itemName, lstDeptReqDetId, lstAllocatedQty);
                }
                lblMessage.Text = "Changes have been updated successfully";
                HideFields();
                DeptQtyGrid.Visible = false;
            }
            catch (AllocateQtyMoreThanActualQtyException ex)
            {
                lblMessage.Text = "Allocate Qty must not be more than Actual Qty";
            }
            catch (TotalAllocatedQtyMustBeEqualTotalActualQtySubtractAdjustedQtyException ex)
            {
                lblMessage.Text = "Total Allocate Qty must be equal to Total Actual Qty subtract adjusted quantity";
            }
            catch (Exception ex)
            {
            }
        }

        private void PopulateCollectionPoint()
        {
            List<CollectionPoint> collectionPoints = dListCont.getCollectionPointNamesCont();
            CollectionPointddl.DataValueField = "CollectionPointID";
            CollectionPointddl.DataTextField = "CollectionPointName";
            CollectionPointddl.DataSource = collectionPoints;
            CollectionPointddl.DataBind();
        }

        private void PopulateCategory()
        {
            List<Category> categories = dListCont.getCategoriesCont();
            Categoryddl.DataValueField = "CategoryID";
            Categoryddl.DataTextField = "CategoryName";
            Categoryddl.DataSource = categories;
            Categoryddl.DataBind();
        }

        private void PopulateItemName()
        {
            int catId = Convert.ToInt32(Categoryddl.SelectedValue);
            List<Stationery> items = dListCont.getStationeryNamesCont(catId);
            ItemNameddl.DataValueField = "ItemCode";
            ItemNameddl.DataTextField = "ItemName";
            ItemNameddl.DataSource = items;
            ItemNameddl.DataBind();
        }

        private void HideFields()
        {                           
            btnAllocate.Visible = false;
            HideAjustmentFields();
        }

        private void HideAjustmentFields()
        {
            Label5.Visible = false;
            txtAdjusmentQty.Visible = false;
            btnAllocate.Visible = false;
        }

        private void ShowAdjustmentFields()
        {
            Label5.Visible = true;
            txtAdjusmentQty.Visible = true;
            btnAllocate.Visible = true;
        }
    }
}